package com.yuebook.smartrpc.framework.invoker;

import com.yuebook.smartrpc.framework.model.InvokerService;
import com.yuebook.smartrpc.framework.zookeeper.IRegisterCenterInvoker;
import com.yuebook.smartrpc.framework.zookeeper.RegisterCenter;
import java.lang.reflect.InvocationHandler;
import org.omg.CORBA.portable.InvokeHandler;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

/**
 * @author honglei
 * @date 2018/11/18 下午9:03
 */
public class InvokerFactoryBean implements FactoryBean, InitializingBean {

    private Class<?> targetItf;

    private Object serviceObj;

    private long timeout;

    private String remoteAppKey;

    private String groupName;


    @Override
    public Object getObject() throws Exception {
        return serviceObj;
    }

    @Override
    public Class<?> getObjectType() {
        return targetItf;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        IRegisterCenterInvoker registerCenter = RegisterCenter.singleton();
        //初始化服务提供者数据
        registerCenter.initServiceMetaData(remoteAppKey, groupName);
        //初始化netty channel

        //获取代理对象
        InvokerProxyBeanFactory handler = InvokerProxyBeanFactory.singleton(targetItf, timeout);
        this.serviceObj = handler.getProxy();
        //注册消费者
        InvokerService invokerService = new InvokerService();
        invokerService.setServiceItf(targetItf);
        invokerService.setRemoteAppKey(remoteAppKey);
        invokerService.setGroup(groupName);
        registerCenter.registerInvokerService(invokerService);
    }

    public Class<?> getTargetItf() {
        return targetItf;
    }

    public void setTargetItf(Class<?> targetItf) {
        this.targetItf = targetItf;
    }

    public Object getServiceObj() {
        return serviceObj;
    }

    public void setServiceObj(Object serviceObj) {
        this.serviceObj = serviceObj;
    }

    public long getTimeout() {
        return timeout;
    }

    public void setTimeout(long timeout) {
        this.timeout = timeout;
    }

    public String getRemoteAppKey() {
        return remoteAppKey;
    }

    public void setRemoteAppKey(String remoteAppKey) {
        this.remoteAppKey = remoteAppKey;
    }

    public String getGroupName() {
        return groupName;
    }

    public void setGroupName(String groupName) {
        this.groupName = groupName;
    }
}
